import classNames from 'classnames'
import './index.scss'
import { useEffect, useMemo, useState } from 'react'
import { billTypeToName } from '@/contants'
import Icon from '@/components/Icon'
import {DeleteOutline } from 'antd-mobile-icons'
import { deleteBillList, fetchBillList } from '@/store/modules/billStore'
import { useDispatch } from 'react-redux'
import { Popconfirm } from 'antd'

const DailyBill = ({ date, billList }) => {
    // 计算支出、收入、结余
    const billResult = useMemo(() => {
        const pay = billList ? billList.filter(item => item.type === 'pay').reduce((a, c) => a + c.money, 0) : 0
        const income = billList ? billList.filter(item => item.type === 'income').reduce((a, c) => a + c.money, 0) : 0
        const total = pay + income
        return {
            pay,
            income,
            total
        }

    }, [billList])

    // 控制列表显示
    const [visible, setVisible] = useState(false)

    // 删除账单
    const dispatch = useDispatch()
    const deleteDayBill = (id) => {
      // console.log(id);
      dispatch(deleteBillList(id))
      fetchBillList()
    }

  return (
    <div className={classNames('dailyBill')}>
      <div className="header">
        <div className="dateIcon">
          <span className="date">{date}</span>
          <span className={classNames('arrow', visible && 'expand')} onClick={() => setVisible(!visible)}></span>
        </div>
        <div className="oneLineOverview">
          <div className="pay">
            <span className="type">支出</span>
            <span className="money">{ billResult.pay.toFixed(2) }</span>
          </div>
          <div className="income">
            <span className="type">收入</span>
            <span className="money">{ billResult.income.toFixed(2) }</span>
          </div>
          <div className="balance">
            <span className="money">{ billResult.total.toFixed(2) }</span>
            <span className="type">结余</span>
          </div>
        </div>
      </div>
      {/* 单日列表 */}
    <div className="billList" style={{ display: visible ? 'block' : 'none'}}>
    {billList.map(item => {
        return (
        <div className="bill" key={item.id}>
            {/* 图标 */}
            <Icon type={item.useFor}/>
            <div className="detail">
            <div className="billType">{billTypeToName[item.useFor]}</div>
            </div>
            <div className={classNames('money', item.type)}>
            {item.money.toFixed(2)}
            </div>
            &nbsp&nbsp
            <Popconfirm
              title="删除账单"
              description="确定要删除吗?"
              onConfirm={() => deleteDayBill(item.id)}
              okText="是"
              cancelText="否"
            >
              <DeleteOutline/>
            </Popconfirm>
        </div>
        )
    })}
    </div>
    </div>
  )
}
export default DailyBill